<?php


namespace app\unify\model;


use think\Model;
use think\model\concern\SoftDelete;
use think\Paginator;

abstract class Base extends Model
{


    protected $pk = "id";

    protected $readonly = ['id', 'gmt_create', 'gmt_modified'];

    protected $hidden = ['deleted'];

    protected $strict = true;

    protected $convertNameToCamel = true;

    //假删除通用字段
    use SoftDelete;

    protected $defaultSoftDelete = 0;
    protected $deleteTime = 'deleted';

    const PLATFORM_ADMIN = 'admin';
    const PLATFORM_CLIENT = 'client';

    const PLATFORM_LIST = [
        self::PLATFORM_ADMIN => '管理端',
        self::PLATFORM_CLIENT => '客户端',
    ];

    public static function getPrimaryKey()
    {
        return app(static::class)->getPk();
    }

    /**
     * @Notes 自动转换主键类型，避免雪花ID精度丢失
     * @Author EdwardCho
     * @Date 2023/12/9
     * @Time 17:18
     * @Interface getIdAttr
     * @param $value
     * @return string
     */
    public function getIdAttr($value)
    {
        return strval($value);
    }

//    protected $autoWriteId = true;
//    protected function autoWriteId()
//    {
//        // 假设在公共函数文件中定义了uuid函数
//        $snowflake = new \Godruoyi\Snowflake\Snowflake();
//        return $snowflake->id();
//    }

    public static function onBeforeInsert(Model $model)
    {
        // 假设在公共函数文件中定义了uuid函数
        $snowflake = new \Godruoyi\Snowflake\Snowflake();
        $model->set("id", $snowflake->id());

        return $model;
    }

    public static function toTreeList($list, $titleName, $idName = 'id', $pidName = 'pid', $parentId = 0, $leftStr = "|——", $appendStr = "——")
    {
        $data = [];

        foreach ($list as $v) {
            if ($v[$pidName] == $parentId) {
                $v[$titleName] = $leftStr . $v[$titleName];
                $data[] = $v;
                $ch = self::toTreeList($list, $titleName, $idName, $pidName, $v[$idName], $leftStr . $appendStr);
                $data = array_merge($data, $ch);
            }
        }
        return $data;
    }

    public static function toTree($list, $idName = 'id', $pidName = 'pid', $parentId = 0)
    {
        $data = [];

        foreach ($list as $v) {
            if ($v[$pidName] == $parentId) {
                $v['children'] = self::toTree($list, $idName, $pidName, $v[$idName]);
                $data[] = $v;
            }
        }
        return $data;
    }


}